package cn.net.lisong.blog.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.net.lisong.blog.po.UserPO;
import cn.net.lisong.blog.service.UserService;
import cn.net.lisong.blog.utils.BeanFactory;
import cn.net.lisong.blog.utils.XUtils;

/**
 * @author lisong
 * 用户相关
 * path /user/*
 */
public class UserServlet  extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final String BASE_DIR = "/WEB-INF/pages/user";
	
	private UserService userService = (UserService) BeanFactory.getBean("userService");
	
	private Log log = LogFactory.getLog(UserServlet.class);
			
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String uri = req.getRequestURI();
		log.debug(uri);
		String[] path = uri.split("/");
		String action = path[path.length -1];
		String xx = String.format("%s/%s.jsp", BASE_DIR, action);
		
		req.getRequestDispatcher(xx).forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String uri = req.getRequestURI();
		log.debug(uri);
		String[] path = uri.split("/");
		String action = path[path.length -1];
		if ("sign_up".equalsIgnoreCase(action)) {
			String email = req.getParameter("username");
			String password = req.getParameter("password");
			String passwordx = req.getParameter("password");
			
			if (XUtils.isBlank(email, password, passwordx) || !password.equals(passwordx)) {
				
				String p = req.getContextPath();
				resp.sendRedirect(p + "/user/sign_up?error=true");
			}  else {
				UserPO user = new UserPO();
				user.setId(XUtils.uuid());
				user.setPassword(passwordx);
				user.setUsername(email);
				userService.save(user );
				String xx = String.format("%s/%s.jsp", BASE_DIR, "sign_success");
				req.getRequestDispatcher(xx).forward(req, resp);
			}
		}
			
	}

}
